package com.xyh.builder;

import com.xyh.bean.Constants;
import com.xyh.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;


public class BuildBase {

    private static final Logger logger = LoggerFactory.getLogger(BuildBase.class);
    public static void execute() {
        List<String> importList = new ArrayList<>();
        //Utils包
        importList.add("package " + Constants.PACKAGE_UTILS);
        build(importList,"DateUtils", Constants.PATH_UTILS);
        build(importList,"DigestUtils", Constants.PATH_UTILS);
        importList.clear();
        //Enums包
        importList.add("package " + Constants.PACKAGE_ENUMS );
        build(importList,"DateTimeUnit", Constants.PATH_ENUMS);
        build(importList,"PageSize", Constants.PATH_ENUMS);
        build(importList,"StatusCode", Constants.PATH_ENUMS);
        importList.clear();

        //Mapper包
        importList.add("package " + Constants.PACKAGE_MAPPER );
        build(importList,"BaseMapperEx", Constants.PATH_MAPPER);
        importList.clear();

        //Query包
        importList.add("package " +Constants.PACKAGE_PARAM );
        build(importList,"BaseQuery", Constants.PATH_PARAM);
        importList.clear();

        //SimplePage 依赖于PageSize
        importList.add("package " + Constants.PACKAGE_PARAM );
        importList.add("import " + Constants.PACKAGE_ENUMS + ".PageSize" );
        build(importList,"SimplePage", Constants.PATH_PARAM);
        importList.clear();

        //VO包
        importList.add("package " + Constants.PACKAGE_VO );
        build(importList,"PaginationResultVO", Constants.PATH_VO);
        build(importList,"LoginUserVO",Constants.PATH_VO);

        importList.add("import "+Constants.PACKAGE_ENUMS+".StatusCode");
        build(importList,"ResultVO",Constants.PATH_VO);
        importList.clear();

        //config包
        importList.add("package " + Constants.PACKAGE_CONFIG );
        build(importList,"CaptchaConfig",Constants.PATH_CONFIG);
        importList.clear();

        //异常包
        importList.add("package " + Constants.PACKAGE_EXCEPTION );
        build(importList,"BusinessException",Constants.PATH_EXCEPTION);
        importList.clear();

        //Controller包
        importList.add("package " + Constants.PACKAGE_CONTROLLER );
        importList.add("import " +Constants.PACKAGE_VO+".ResultVO");
        importList.add("import " +Constants.PACKAGE_ENUMS+".StatusCode");
        build(importList,"ABaseController",Constants.PATH_CONTROLLER);
        importList.add("import " +Constants.PACKAGE_EXCEPTION+".BusinessException");
        build(importList,"AGlobalExceptionHandlerController",Constants.PATH_CONTROLLER);
        importList.clear();
    }

    private static void build(List<String> importList, String fileName, String outPutPath) {
        // 初始化目录和文件
        File poDir = new File(outPutPath);
        if (!poDir.exists() && !poDir.mkdirs()) {
            logger.error("创建BuildBase目录失败: {}", outPutPath);
            return;
        }

        File javaFile = new File(outPutPath, fileName + ".java");

        // 声明所有需要关闭的资源
        try (
                // 输出流
                OutputStream out = new FileOutputStream(javaFile);
                OutputStreamWriter outW = new OutputStreamWriter(out, StandardCharsets.UTF_8);
                BufferedWriter bw = new BufferedWriter(outW);

                // 输入流，使用getResourceAsStream直接获取流，避免使用getPath
                InputStream in = BuildBase.class.getClassLoader().getResourceAsStream("template/" + fileName + ".txt");
                InputStreamReader inR = new InputStreamReader(in, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(inR)
        ) {
            // 写入package和import语句
            for (String importStr : importList) {
                if (!StringUtils.isEmpty(importStr) && importStr.startsWith("package")) {
                    bw.write(importStr + ";");
                    bw.newLine();
                    bw.newLine();
                } else {
                    bw.write(importStr + ";");
                    bw.newLine();
                }
            }

            // 写入模板内容
            String line;
            while ((line = br.readLine()) != null) {
                bw.write(line);
                bw.newLine();
            }

            bw.flush();
            logger.info("生成{}成功：{}", fileName, javaFile.getAbsolutePath());
        } catch (Exception e) {
            logger.error("生成{}失败：{}", fileName, javaFile.getAbsolutePath(), e);
        }
    }
}